<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js类之内置类继承</title>
</head>
<body>
  <ul>
    <li>可使用extends继承内置类(如Array，Number等),以达到复用现有类的同时扩展新的功能</li>
  </ul>
  <script>
    console.log('****************用class定义类****************')
    {
      class MyArray extends Array {
        constructor(...args) {
          super(...args)
        }
        first() {
          return this[0]
        }
        max() {
          return this.sort((a, b) => b - a)[0]
        }
      }
      const arr = new MyArray(10, 4, 23, 36, 18, 8, 9)
      console.log(arr)             // MyArray(7) [10, 4, 23, 36, 18, 8, 9]
      console.log(arr.first())     // 10
      console.log(arr.max())       // 36
    }
    console.log('****************用function定义类****************')
    {
      function MyArray(...args) {
        args.forEach(item => this.push(item))
      }
      MyArray.prototype = Object.create(Array.prototype)
      Object.defineProperty(MyArray.prototype, 'constructor', {
        value: MyArray,
        enumerable: false
      })
      MyArray.prototype.first = function () {
        return this[0]
      }
      MyArray.prototype.max = function () {
        return this.sort((a, b) => b - a)[0]
      }
      const arr = new MyArray(10, 4, 23, 36, 18, 8, 9)
      console.log(arr)             // MyArray(7) [10, 4, 23, 36, 18, 8, 9]
      console.log(arr.first())     // 10
      console.log(arr.max())       // 36
    }
  </script>
</body>
</html>